# coding=utf-8
import json
import time

import requests

# reload(sys)
# sys.set setdefaultencoding('utf-8')

c_cookies = 'BAIDUID=9652EE90A747FF881874BD2EFA97BED2:FG=1; BIDUPSID=9652EE90A747FF881874BD2EFA97BED2; PSTM=1499924674; FP_UID=3510b5fd16fb7f20a37a50e46151c7cf; BDUSS=1VERWY4N3NjeTl-MjRoaFdmRTVtazV3aXdSS0huZFJMTUlVOUl5enB4MGkzcUJhQVFBQUFBJCQAAAAAAAAAAAEAAABEe2cmd2luZHnJo9ChxdYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACJReVoiUXlaa; BDRCVFR[LjBW2AN_qnc]=Ao3Q-Pds4vDnHD3IvD8mvqV; H_PS_PSSID=; PSINO=5'
headers = {
    'Host': 'pet-chain.baidu.com',
    'Connection': 'keep-alive',
    'Accept': 'application/json',
    'Origin': 'https://pet-chain.baidu.com',
    'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Mobile Safari/537.36',
    'Content-Type': 'application/json',
    'Referer': 'https://pet-chain.baidu.com',
    'Accept-Encoding': 'gzip, deflate, br',
    'Accept-Language': 'zh-CN,zh;q=0.9',
    'Cookie': c_cookies}


def recall(pet_id):
    url = 'https://pet-chain.baidu.com/data/market/unsalePet'
    timestamp = int(round(time.time() * 2000))
    payload = {"petId": pet_id, "requestId": timestamp, "appId": 1, "tpl": ""}
    res = requests.post(url, data=json.dumps(payload), headers=headers)
    # return json.loads(res.content)['errorMsg']
    emsg = json.loads(res.content)['errorMsg']
    print('撤回: ' + emsg)
    return emsg


def sell(pet_id, amount):
    url = 'https://pet-chain.baidu.com/data/market/salePet'
    timestamp = int(round(time.time() * 1000))
    payload = {"petId": pet_id, "amount": amount, "requestId": timestamp, "appId": 1, "tpl": ""}
    res = requests.post(url, data=json.dumps(payload), headers=headers)
    emsg = json.loads(res.content)['errorMsg']
    print('以' + str(amount) + '售出: ' + emsg)


# petId = "1855391649572853499"   // 3499
petId = "1858365416210322619"     # 3499

while True:
    sell(petId, 3499)
    time.sleep(1)
    recall(petId)
    sell(petId, 19999)
    time.sleep(5)
    msg = recall(petId)

    if "有人购买" in msg:
        break

    time.sleep(2)
